<template>
  <div class="app-container">
  <el-row :gutter="20">

    <!--仓库选择-->
      <div class="head-container">
        <el-drawer
          title="选择仓库"
          size="18%"
          :visible.sync="drawer"
          :direction="direction"
          >
          <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
          v-hasRole ="['admin','department']"
        />
        <el-button style="margin-top:20px;position:relative;left:25%;" type="info" icon="el-icon-search" size="mini" @click="resetChecked">查看所有</el-button>
        </el-drawer>
      </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="typeId">
          <el-select style="display:flex;" v-model="queryParams.typeId" clearable placeholder="请选择" >
              <el-option
                v-for="opt in options_itemType"
                :key="opt.typeId"
                :label="opt.typeName"
                :value="opt.typeId"
                :span="8">
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          size="mini"
          plain
          icon="el-icon-search"
          @click="drawer = true"
          v-hasRole="['department']"
          >选择仓库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleApplyItem"
          v-hasRole="['group']"
          v-if = "!$store.getters.roles.includes('admin')"
        >新物品申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleAdd"
          v-hasRole="['department']"
          v-if = "!$store.getters.roles.includes('admin')"
        >入库登记</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehousemanager:item:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

    </el-row>

    <el-table ref="table" v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="序号" align="center" width="55" type="index" :index.sync="indexMethod" />
      <el-table-column label="ID"       width="55" align="center" prop="itemId" v-if="false"/>
      <el-table-column label="物品名称" width="150"  align="center" prop="itemName" />
      <el-table-column label="物品数量" width="100"  align="center" prop="itemNum" />
      <el-table-column label="计量单位" width="100"  align="center" prop="itemUnit" />
      <el-table-column label="所属类型" width="130"  align="center" prop="itemType.typeName" />
      <el-table-column label="更新时间" width="150"  align="center" prop="updateTime" sortable/>
      <el-table-column label="所属仓库" width="120"  align="center" prop="sysDept.deptName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehousemanager:item:edit']"
            v-if="scope.row.deptId == $store.getters.deptId ? true:false"
          >盘点</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdd(scope.row)"
            v-hasRole="['department']"
            v-if="scope.row.deptId == $store.getters.deptId ? true:false"
          >入库登记</el-button>
          <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleOutwarehouse(scope.row)"
          v-hasPermi="['warehousemanager:outwarehouse:add']"
          v-if="scope.row.deptId == $store.getters.deptId ? true:false"
        >出库登记</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOperate(scope.row)"
            v-hasRole="['department']"
            v-if="scope.row.deptId == $store.getters.deptId ? true:false"
          >外库操作</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleApplyItem(scope.row)"
            v-hasRole="['group']"
            v-if="scope.row.deptId == $store.getters.deptId ? true:false"
          >物资申请</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleApplyOperate(scope.row)"
            v-hasRole="['group']"
            v-if="scope.row.deptId == $store.getters.deptId ? true:false"
          >外库申请</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasRole="['admin']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-row>

    <!-- 物资申请及外库申请 -->
    <el-dialog :title="title" :visible.sync="openApply" width="55%" append-to-body @close="cancelApply">
      <div style="display:flex;text-align:center;justify-content:center">
        <el-form ref="formApply" :model="formApply" :rules="rules.applyRules" label-width="80px" style="width : 70%">
          <el-form-item label="物品名称" prop="itemName" >
            <el-col >
                <el-input v-model="formApply.itemName" placeholder="请输入物品名称" :disabled="disabled" />
            </el-col>
          </el-form-item>
          <el-form-item label="物品数量" prop="itemNum">
            <el-col >
                <el-input v-model.number="formApply.itemNum" placeholder="请输入物品数量" />
            </el-col>
          </el-form-item>
          <el-form-item label="申请类型" prop="applyType" >
            <el-select style="display:flex;" v-model="formApply.applyType" clearable placeholder="请选择" :disabled="true">
              <el-option
                v-for="opt in options_applyType"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-show = "formApply.applyType == '0'" label="外库类型" prop="applyOperateType">
            <el-select style="display:flex;" v-model="formApply.applyOperateType" clearable placeholder="请选择" >
              <el-option
                v-for="opt in options_operateType"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
                :span="8">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间" prop="checkApplicationTime">
            <el-date-picker clearable style="display:flex;width:auto;"
              v-model="formApply.checkApplicationTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择申请时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="申请人" prop="checkApplicant">
            <el-col>
                <el-input v-model="formApply.checkApplicant" :disabled="true"/>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">申请</el-button>
        <el-button @click="cancelApply">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="物资盘点" :visible.sync="openUpdate" width="55%" append-to-body>
      <div style="display:flex;text-align:center;justify-content:center">
        <el-form ref="formUpdate" :model="formUpdate" :rules="rules.updateRules" label-width="80px" style="width : 70%">
          <el-form-item label="物品名称" prop="itemName" >
            <el-col >
                <el-input v-model="formUpdate.itemName" placeholder="请输入物品名称" :disabled="true" />
            </el-col>
          </el-form-item>
          <el-form-item label="物品数量" prop="itemNum">
            <el-col >
                <el-input v-model.number="formUpdate.itemNum" placeholder="请输入物品数量" />
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateForm">确认</el-button>
        <el-button @click="cancelUpdate">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="入库登记" :visible.sync="openInsert" width="55%" append-to-body>
      <div style="display:flex;text-align:center;justify-content:center">
        <el-form ref="formInsert" :model="formInsert" :rules="rules.insertRules" label-width="80px" style="width : 70%">
          <el-form-item label="物品名称" prop="itemName" >
            <el-col >
                <el-input v-model="formInsert.itemName" placeholder="请输入物品名称"  />
            </el-col>
          </el-form-item>
          <el-form-item label="物品数量" prop="itemNum">
            <el-col >
                <el-input v-model.number="formInsert.itemNum" placeholder="请输入物品数量" />
            </el-col>
          </el-form-item>
                <el-form-item label="物品单位" prop="itemUnit">
            <el-col >
                <el-input v-model.number="formInsert.itemUnit" placeholder="请输入单位名称" />
            </el-col>
          </el-form-item>
          <el-form-item label="物品类型" prop="typeId">
              <el-select style="display:flex;" v-model="formInsert.typeId" clearable placeholder="请选择" >
              <el-option
                v-for="opt in options_itemType"
                :key="opt.typeId"
                :label="opt.typeName"
                :value="opt.typeId"
                :span="8">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInsertForm">确认</el-button>
        <el-button @click="cancleInsert">取 消</el-button>
      </div>
    </el-dialog>

 <!-- 外库操作 -->
    <el-dialog title="外库操作" :visible.sync="openOperate" width="55%" append-to-body>
      <div style="display:flex;text-align:center;justify-content:center">
        <el-form ref="formOperate" :model="formOperate" :rules="rules.operateRules" label-width="80px" style="width : 70%">
          <el-form-item label="物品名称" prop="itemName" >
            <el-col >
              <el-input v-model="formOperate.itemName" placeholder="请输入物品名称" :disabled="true" />
            </el-col>
          </el-form-item>
          <el-form-item label="物品数量" prop="itemNum">
            <el-col >
              <el-input v-model.number="formOperate.itemNum" placeholder="请输入物品数量" />
            </el-col>
          </el-form-item>
          <el-form-item label="操作时间" prop="operateTime">
            <el-date-picker clearable style="display:flex;width:auto;"
                            v-model="formOperate.operateTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择操作时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="操作类型" prop="operateType">
            <el-select style="display:flex;" v-model="formOperate.operateType" clearable placeholder="请选择" >
              <el-option
                v-for="opt in options_operateType"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
                :span="8">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOperateForm">确认</el-button>
        <el-button @click="cancelOperate">取 消</el-button>
      </div>
    </el-dialog>
       <!--    出库登记-->
    <el-dialog  :title="title" :visible.sync="openOut" width="55%" append-to-body>
      <div style="display:flex;text-align:center;justify-content:center">
        <el-form ref="outForm" :model="outForm" :rules="rules.outRules" label-width="80px" style="width : 70%">
          <el-form-item label="物品名称" prop="itemName" >
            <el-col >
              <el-input v-model="outForm.itemName" :disabled="true"/>
            </el-col>
          </el-form-item>
          <el-form-item label="物品数量" prop="itemNum">
            <el-col >
              <el-input v-model="outForm.itemNum" placeholder="请输入物品数量"/>
            </el-col>
          </el-form-item>
          <el-form-item label="出库仓库" prop="outWarehouseName">
            <el-input v-model="outForm.outWarehouseName" :disabled="true"/>
          </el-form-item>
          <el-form-item label="出库时间" prop="outTime">
            <el-date-picker clearable style="display:flex;width:auto;"
                            v-model="outForm.outTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择出库时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="是否归还" prop="isReturn">
            <el-radio-group v-model="outForm.isReturn" size="medium" style="float:left;margin-top:10px;">
              <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="登记人" prop="checkApplicant">
            <el-col>
              <el-input v-model="outForm.checkApplicant" :disabled="true"/>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOutForm">确认</el-button>
        <el-button @click="cancelOut">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem ,listType} from "@/api/warehousemanager/item";
import {addCheck} from "@/api/warehousemanager/check";
import {addOperate} from "@/api/warehousemanager/operate";
import {addOutwarehouse} from "@/api/warehousemanager/outwarehouse";
import {getInfo} from "@/api/login";
import {deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Item",
  components: { Treeselect },
  data() {
    const checkNum = (rule, value, callback) => {
      if (this.numForm.warehouseNum <value) {
        callback(new Error("出库数量不得超过库存数量"));
      } else {
        callback();

      }
    };
    const operateNum = (rule, value, callback) => {
      if (this.numForm.warehouseNum <value) {
        callback(new Error("外库操作数量不得超过库存数量"));
      } else {
        callback();

      }
    };
        //外库申请数量校验
    const checkOperateApplyNum = (rule, value, callback) =>{
      if(this.formApply.stock < value ){
        callback(new Error("申请数量不得超过库存数量"));
      }else{
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 易耗品管理表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      //表内禁用物品名
      disabled:false,
      // 是否显示弹出层
      openApply: false,
      openUpdate:false,
      openInsert:false,
      openOut:false,
      openOperate:false,
      //中间变量
      dept:null,
      itemName:null,
      // 部门树选项
      deptOptions: undefined,
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      drawer: false,
      direction: 'ltr',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: null,
        deptId:this.$store.getters.deptId,
        typeId:null,
      },
      // 申请表单参数
      formApply: {
        itemId:null,
        itemName:null,
        deptId:this.$store.getters.deptId,
        itemNum: null,
        checkApplicant: this.$store.getters.name,
        checkApplicationTime: null,
        applyType: null,
        applyOperateType: null,
        status:'2',
        checkRemark:null,
        //检查量
        stock:Infinity
      },
      //盘点表单参数
      formUpdate:{
        itemId:null,
        itemName:null,
        itemNum: null,
      },
      //登记入库
      formInsert:{
          itemId:null,
          itemName:null,
          itemNum: null,
          itemUnit:null,
          deptId:this.$store.getters.deptId,
          typeId:null
      },
      //外库操作表单参数
      formOperate:{
        itemId:null,
        itemName:null,
        itemNum: null,
        operateTime:null,
        operateType: null,
        deptId:this.$store.getters.deptId,
      },
      // 出库表单参数
      outForm: {
        itemName:null,
        deptId:this.$store.getters.deptId,
        toWarehouseId:this.$store.getters.deptId,
        itemNum: null,
        itemId:null,
        checkApplicant: this.$store.getters.name,
        checkApplicationTime: null,
        outTime:null,
        applyType: null,
        applyOperateType: null,
        outWarehouseName:null,//出库仓库
        status:null,
        isReturn:null,
        returnNum: 0,
        // outNum:0
      },
      //获取库存数量
      numForm:{
        // 初始仓库库存
        warehouseNum:0
      },
      //申请类型选择
      options_applyType: [{
          value: '1',
          label: '物资申请'
        }, {
          value: '0',
          label: '外库申请'
        }],
      //外库操作类型选择
      options_operateType: [{
          value: '0',
          label: '报修'
        }, {
          value: '1',
          label: '报废'
        },{
          value: '2',
          label: '收回'
        }],

      options_itemType:null,
      //归还状态选择
      statusOptions: [{
        "label": "是",
        "value": 1
      }, {
        "label": "否",
        "value": 0
      }],
      // 表单校验
      rules: {
        //申请表单检验
        applyRules:{
          itemName: [
            { required: true, message: '请输入物品名称', trigger: 'blur' },
            { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur' },
          ],
          itemNum: [
            { required: true, message: '请输入物品数量' },
            {pattern:/^[1-9]\d*$/,message:'数量必须为数字值'},
            { required: true, validator: checkOperateApplyNum, trigger: "blur" }
          ],
          checkApplicationTime: [
            { required: true, message: '请选择申请日期', trigger: 'change' }
          ],
        },
        updateRules:{
          itemName: [
            { required: true, message: '请输入物品名称', trigger: 'blur' },
          ],
          itemNum: [
            { required: true, message: '请输入物品数量' },
            {pattern:/^[1-9]\d*$/,message:'数量必须为数字值'},
          ],
        },
        //入库表单校验
        insertRules:{
          itemName: [
            { required: true, message: '请输入物品名称', trigger: 'blur' },
            { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur' },
          ],
          itemNum: [
            { required: true, message: '请输入物品数量' },
            {pattern:/^[1-9]\d*$/,message:'数量必须为数字值'},
          ],
          itemUnit: [
            { required: true, message: '请输入数量单位', trigger: 'blur' },
          ],
          typeId:[
             { required: true, message: '请选择物品类型', trigger: 'blur' },
          ]
        },
        //外库操作表单校验
        operateRules: {
          itemName: [
            { required: true, message: '请输入物品名称', trigger: 'blur' },
          ],
          itemNum: [
            { required: true, message: '请输入物品数量' },
            {pattern:/^[1-9]\d*$/,message:'数量必须为数字值'},
            { required: true, validator: operateNum, trigger: "blur" }
          ],
          operateTime: [
            { required: true, message: '请选择操作日期', trigger: 'change' }
          ],
          operateType: [
            { required: true, message: '请选择操作类型', trigger: 'change' }
          ],
        },
              //出库表单校验
        outRules: {
          itemNum: [
            { required: true,message: "出库数量不能为空", trigger: "blur" },
            {pattern:/^[1-9]\d*$/,message:'数量必须为数字值'},
            { required: true, validator: checkNum, trigger: "blur" }
          ],
          outWarehouseName: [{
            required: true,
          }],
          checkApplicationTime: [{
            required: true,
            // message: '请选择出库日期',
            trigger: 'change'
          }],
          outTime: [{
            required: true,
            message: '请选择出库日期',
            trigger: 'change'
          }],

          isReturn: [{
            required: true,
            message: '是否归还不能为空',
            trigger: 'change'
          }],

        }
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTypeList();
    this.getDeptTree();
  },
  methods: {
    //自增序号
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询易耗品管理列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**查询易耗品类型列表 */
    getTypeList(){
      listType().then(res=>{
        this.options_itemType = res.data;
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      if((this.$store.getters.roles.includes("admin") || this.$store.getters.roles.includes("department")) ){
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      }

    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
      this.drawer = false;
    },
    //节点重置事件
    resetChecked() {
      this.queryParams.deptId=null;
      this.handleQuery();
      this.drawer = false;
    },
    // 申请表单重置
    resetApply() {
      this.formApply ={
        itemId:null,
        itemName:null,
        deptId:this.$store.getters.deptId,
        itemNum: null,
        checkApplicant: this.$store.getters.name,
        checkApplicationTime: null,
        applyType: null,
        applyOperateType: null,
        status:'2',
        checkRemark:null,
        //检查量
        stock:Infinity
      }
      this.resetForm("formApply");
    },
    //盘点表单重置
    resetUpdate(){
      this.formUpdate={
        itemId:null,
        itemName:null,
        itemNum: null,
      }
      this.resetForm("formUpdate")
    },
    //入库表单重置
    resetInsert(){
      this.formInsert={
          itemId:null,
          itemName:null,
          itemNum: null,
          itemUnit:null,
          deptId:this.$store.getters.deptId,
          typeId:null
      }
      this.resetForm("formInsert")
    },
    // 申请取消按钮
    cancelApply() {
      this.openApply = false;
      this.disabled = false;
      this.resetApply();
    },
    //盘点取消按钮
    cancelUpdate() {
      this.openUpdate = false;
      this.resetUpdate();
    },
    //入库登记取消按钮
    cancleInsert(){
      this.openInsert = false;
      this.resetInsert();
    },
    //外库操作取消按钮
    cancelOperate() {
      this.openOperate = false;
      this.reset();
    },
    //出库取消按钮
    cancelOut() {
      this.openOut = false;
      this.disabled = false;
      this.resetOut();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //出库表单重置
    resetOut() {
      this.resetForm("outForm");
    },
    //根据所选出库仓库获取对应的warehouseId
    handleChange(data){
      this.outForm.deptId=this.$refs["cascaderOut"].getCheckedNodes()[0].value
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 盘点操作 */
    handleUpdate(row) {
      this.resetUpdate();
      this.formUpdate.itemId = row.itemId;
      this.formUpdate.itemName = row.itemName;
      this.formUpdate.itemNum =  row.itemNum;
      this.openUpdate = true;
    },
    /** 物资申请按钮操作 */
    handleApplyItem(row) {
      this.resetApply();
      this.openApply = true;
      if (row.itemName != null){
        this.disabled = true;
        this.formApply.itemName = row.itemName;
        this.formApply.itemId = row.itemId;
      }
      this.formApply.applyType= '1';
      this.title = "物资申请";
    },
    /** 外库申请按钮操作*/
    handleApplyOperate(row){
      this.resetApply();
      this.openApply= true;
      if (row.itemName != null){
        this.disabled = true;
        this.formApply.itemName = row.itemName;
        this.formApply.itemId = row.itemId;
        this.formApply.itemNum =row.itemNum;
        this.formApply.stock = row.itemNum;
      }
      this.formApply.applyType= '0';
      this.title = "外库申请";
    },
    /**入库登记 */
    handleAdd(row){
      this.openInsert = true;
      this.resetInsert();
      if (row.itemId != null){
        this.formInsert.itemId =row.itemId;
        this.formInsert.itemName = row.itemName;
        this.formInsert.itemUnit = row.itemUnit;
        this.formInsert.typeId = row.typeId;
      } 
    },
    /** 外库操作 */
    handleOperate(row) {
      this.resetForm("formOperate");
      this.formOperate.itemId = row.itemId;
      this.formOperate.itemName = row.itemName;
      this.formOperate.itemNum = row.itemNum;
      this.openOperate = true;
      for (let i = 0; i <this.itemList.length; i++) {
        if (this.itemList[i].itemId == this.formOperate.itemId) {
          this.numForm.warehouseNum = this.itemList[i].itemNum;
        }
      }
    },
    /**出库操作*/
    handleOutwarehouse(row){
      this.resetOut();
        this.outForm.itemId= row.itemId;
        this.outForm.itemName = row.itemName;
        this.outForm.itemNum = row.itemNum;
        this.outForm.outWarehouseName = row.sysDept.deptName;
        this.openOut = true;
        this.title = "出库登记";
        this.outForm.status='0';
        for (let i = 0; i <this.itemList.length; i++) {
          if(this.itemList[i].itemId==this.outForm.itemId){
            this.numForm.warehouseNum=this.itemList[i].itemNum;
          }
        }
      // });
    },
    /**删除 */
    handleDelete(row){
      const itemIds = row.itemId || this.ids;
      this.$modal.confirm('是否确认删除物品为"' + row.itemName + '"的数据项？').then(function() {
        return delItem(itemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交申请按钮 */
    submitForm() {
      this.$refs["formApply"].validate(valid=>{
        if (valid){
          addCheck(this.formApply).then(res =>{
              this.$modal.msgSuccess("新增成功");
              this.openApply = false;
              this.disabled = false;
              this.resetApply();
          })
        }
      })
    },

    /** 提交盘点表单 */
    submitUpdateForm(){
      this.$refs["formUpdate"].validate(valid =>{
        if (valid){
            updateItem(this.formUpdate).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openUpdate = false;
              this.getList();
            });
        }
      })
    },
    /**提交入库登记表单 */
    submitInsertForm(){
      this.$refs["formInsert"].validate(valid =>{
        if (valid){
            addItem(this.formInsert).then(res=>{
            this.$modal.msgSuccess("新增成功")
            this.getList();
            this.openInsert = false;
          })
        }
      })
    },
    /** 提交外库操作表单 */
    submitOperateForm(){
      this.$refs["formOperate"].validate(valid =>{
        if (valid){
          addOperate(this.formOperate).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.openOperate = false;
            this.disabled = false;
            this.getList();
          })
          for (let i=0; i<this.itemList.length; i++){
            if (this.itemList[i].itemId==this.formOperate.itemId){
              this.itemList[i].itemNum-=this.formOperate.itemNum;
              this.formOperate.itemNum=this.itemList[i].itemNum;
              this.refresh=true;
            }
          }
          updateItem(this.formOperate).then(res => {
            this.openOut = false;
            this.disabled = false;
            this.getList();
          })
        }
      })
    },

    /** 提交出库登记表单 */
    submitOutForm() {
      this.$refs["outForm"].validate((valid) => {
        if (valid) {
          // Check the value of is_return
          if (this.outForm.isReturn === 1) {
            this.outForm.status = 0;
            this.outForm.returnNum = this.outForm.itemNum;
          } else if (this.outForm.isReturn === 0) {
            this.outForm.status = 3;
            this.outForm.returnNum = 0;
          }
          
          addOutwarehouse(this.outForm)
            .then((res) => {
              this.$modal.msgSuccess("提交成功");
              this.openOut = false;
              this.disabled = false;
            })
            .then(() => {
              // Update item quantity and status
              for (let i = 0; i < this.itemList.length; i++) {
                if (this.itemList[i].itemId === this.outForm.itemId) {
                  this.itemList[i].itemNum = this.numForm.warehouseNum - this.outForm.itemNum;
                  this.outForm.itemNum = this.numForm.warehouseNum - this.outForm.itemNum;
                  this.refresh = true;
                  this.outForm.itemNum = this.itemList[i].itemNum;
                }
              }
              updateItem(this.outForm).then((res) => {
                this.openOut = false;
                this.disabled = false;
                this.getList();
              });
            });
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehousemanager/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>

</style>
